<template>
  <div v-loading="initLoading" :class="{'component-class': pageType === 'component','mobile-create': showMobilePage}" class="create-custom-box">
    <div class="create-customer">
      <el-form v-if="hasRouteAuth('crm:customer:clientInfo:read')" ref="editCustomerForm" :model="editCustomerForm" :rules="editCustomerRules" :label-position="formAlign" class="lineHeight32" label-width="110px" @submit.native.prevent>
        <div class="customer-form">
          <div class="flex title-tip">
            <div>
              <Title :title="title"/>
            </div>
            <p>注意：客户名称和类型保存后无法修改，请填写准确、完整。</p>
          </div>
          <el-row :class="{'response-el-row': !pageType}" :type="!pageType?'flex':''">
            <el-col :span="12" class="responsive-col-medium-8">
              <el-form-item label="客户类型" prop="clientType" class="client-type">
                <el-select v-model="editCustomerForm.clientType" :disabled="isPageEdit && !hasRouteAuth('crm:customer:typeEdit')" size="small" popper-class="global-select-down" name="clientType" @change="checkNameRepeat">
                  <el-option
                    v-for="item in clientList"
                    :key="item.id"
                    :label="item.value"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-medium-8">
              <el-form-item label="客户名称" prop="clientName" class="client-name">
                <template slot="label">
                  <span style="display: inline-flex;align-items: center;">客户名称
                    <InfoIcon :content="canEdit ? '要修改客户名称请联系财务经理' : '请填写客户的真实全称'" style="width: 16px;height: 16px;margin-left: 4px;" />
                  </span>
                </template>
                <div :class="{'width240': (clientCodeRepeat || dupNameCode) && editCustomerForm.clientType}" class="flex-center relative">
                  <el-input
                    :disabled="canEdit"
                    v-model.trim="editCustomerForm.clientName"
                    :maxlength="50"
                    size="small"
                    name="clientName"
                    placeholder="请输入客户的全称"
                    type="text"
                    @change="checkNameRepeat"
                    @input="inputClientName" />
                  <el-input
                    v-if="(clientCodeRepeat || dupNameCode) && editCustomerForm.clientType"
                    v-model.trim="dupNameCode"
                    :disabled="canEdit"
                    placeholder="重名识别号"
                    size="small"
                    maxlength="20"
                    style="width: 95px; margin-left: 8px;"
                    @change="checkNameRepeat" />
                  <el-button
                    v-if="editCustomerForm.clientType?clientCodeRepeat === 2:clientRepeatAuth === 2"
                    size="small"
                    type="primary"
                    style="padding: 7px 3px;margin-left: 4px;"
                    @click="toCreateApproval(editCustomerForm.clientName)">
                    <div class="flex-center">申请协作<tipIcon class="ml5" content="已存在相同名称客户，无需新建客户，请申请协作权限"/></div>
                  </el-button>
                  <div v-if="editCustomerForm.clientName && clientRepeatAuth && editCustomerForm.clientType && !dupNameCode" class="footer-tip">客户名称重复，请输入识别号（建议手机尾号后4位）</div>
                  <div v-if="clientRepeatAuth && !editCustomerForm.clientType && clientRepeatAuth === 1" class="footer-tip">已拥有该客户的权限，请勿重复创建</div>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-medium-8">
              <el-form-item label="客户状态" prop="clientStatus" class="client-type">
                <el-select v-model="editCustomerForm.clientStatus" size="small" popper-class="global-select-down" name="clientStatus" @change="statusChange">
                  <el-option
                    v-for="item in clientStatusList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-medium-8">
              <el-form-item label="客户来源" prop="clientSource" class="client-type">
                <el-input v-model="editCustomerForm.clientSource" :maxlength="50" size="small" name="clientSource" type="text" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-medium-8">
              <el-form-item label="客户行业" prop="clientBusiness">
                <el-input v-model="editCustomerForm.clientBusiness" :maxlength="50" size="small" name="clientBusiness" type="text" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-medium-8">
              <el-form-item label="所属集团">
                <template slot="label">
                  <span style="display: inline-flex;align-items: center;white-space: nowrap;">所属集团
                    <InfoIcon content="输入客户名称超过6个字时才可匹配集团名称" style="width: 16px;height: 16px;margin-left: 4px;" />
                  </span>
                </template>
                <el-select
                  ref="groupSelectRef"
                  v-model="editCustomerForm.groupId"
                  :remote-method="getGroupList"
                  size="small"
                  popper-class="global-select-down"
                  name="groupId"
                  multiple
                  collapse-tags
                  clearable
                  remote
                  filterable
                  @focus="groupFocus">
                  <el-option
                    v-for="item in groupList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-medium-8">
              <el-form-item label="标签" prop="tag">
                <TagSelect v-model="editCustomerForm.tag" :collapse-tags="false" :module-type="TAG_MODULES.SETTLE_CUSTOMER" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-medium-8">
              <el-form-item label="实际客户名称" prop="actualClientRequired">
                <template slot="label">
                  <span style="display: inline-flex;align-items: center;white-space: nowrap;">实际客户名称
                    <InfoIcon content="选择必填后，创建订单选择该客户时，实际客户名称需要必填" style="width: 16px;height: 16px;margin-left: 4px;" />
                  </span>
                </template>
                <el-radio v-model="editCustomerForm.actualClientRequired" :label="1">必填</el-radio>
                <el-radio v-model="editCustomerForm.actualClientRequired" :label="0">非必填</el-radio>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-medium-8">
              <el-form-item label="备注" prop="remark" class="remark">
                <el-input v-model.trim="editCustomerForm.remark" :maxlength="500" size="small" class="client-textarea" name="remark" type="text" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <el-form v-show="hasRouteAuth('crm:customer:levelInfo:read')" ref="levelInfoFormRef" :model="editCustomerForm" :rules="levelRules" :label-position="formAlign" class="lineHeight32" label-width="110px" @submit.native.prevent>
        <div class="customer-form">
          <Title :title="'等级账期'" style="margin: 7px 0 16px;" class="mobile-title-top"/>
          <el-row :class="{'response-el-row': !pageType}" :type="!pageType?'flex':''">
            <el-col :span="12" class="responsive-col-medium-8">
              <el-form-item label="客户等级" prop="clientGrade">
                <template slot="label">
                  <span style="display: inline-flex;align-items: center;">客户等级
                    <InfoIcon content="置灰显示的等级表示你无权限调整，若需设置可保存客户后发起申请" style="width: 16px;height: 16px;margin-left: 4px;" />
                  </span>
                </template>
                <el-select
                  v-model="editCustomerForm.clientGrade"
                  size="small"
                  popper-class="global-select-down">
                  <el-option
                    v-for="item in clientLevelOptions"
                    :key="item.name"
                    :label="item.name"
                    :value="item.name"
                    :disabled="!canSelectLevel(item)" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-medium-8">
              <el-form-item label="欠款额度(元)">
                <el-input v-model.trim="editCustomerForm.oweAmount" disabled placeholder="选择客户等级后将自动填入" size="small" type="text"/>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-medium-8">
              <el-form-item label="欠款账期">
                <el-input
                  v-model.trim="editCustomerForm.accountPeriod"
                  disabled
                  type="number"
                  placeholder="选择客户等级后将自动填入"
                  size="small"
                  @mousewheel.native.prevent>
                  <span slot="suffix" style="margin-right:5px;color:#333;">天</span>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <el-form v-if="hasRouteAuth('crm:customer:invoiceInfo:read')" :model="editCustomerForm" :label-position="formAlign" class="lineHeight32" label-width="110px" @submit.native.prevent>
        <div class="customer-form">
          <Title :title="'开票信息'" style="margin: 7px 0 16px;" class="mobile-title-top"/>
          <el-row :class="{'response-el-row': !pageType}" :type="!pageType?'flex':''">
            <el-col :span="12" class="responsive-col-medium-8">
              <el-form-item :label="editCustomerForm.clientType?'身份证号':'纳税人识别号'">
                <el-input :disabled="canEdit" v-model.trim="editCustomerForm.invoiceInfo.taxpayerNum" :maxlength="20" size="small" type="text" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-medium-8">
              <el-form-item label="开户行">
                <el-input v-model.trim="editCustomerForm.invoiceInfo.openBank" :maxlength="50" size="small" type="text" placeholder="请输入"/>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-medium-8">
              <el-form-item label="开户账号">
                <el-input v-model.trim="editCustomerForm.invoiceInfo.accountNum" :maxlength="50" size="small" type="text" placeholder="请输入"/>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-medium-8">
              <el-form-item label="注册电话">
                <el-input v-model.trim="editCustomerForm.invoiceInfo.phone" :maxlength="50" size="small" type="text" placeholder="请输入"/>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-medium-8">
              <el-form-item label="开票地址">
                <el-input v-model.trim="editCustomerForm.invoiceInfo.invoiceAddress" :maxlength="50" size="small" type="text" placeholder="请输入"/>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-medium-8">
              <el-form-item label="一般纳税人证明">
                <upAttachment
                  ref="uploadAttachment"
                  :hide-confirm="true"
                  :file-list="editCustomerForm.invoiceInfo.taxpayerAttachment"
                  import-api="/common/file/upload"
                  btn-text="上传文件"
                  @complateSetData="completeSetData($event, 'taxpayerAttachment')"
                  @removeFileList="removeFileList($event, 'taxpayerAttachment')" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <DetailTabs v-if="hasRouteAuth(['crm:customer:contactsInfo:read', 'crm:customer:payerInfo:read'])" v-model="activeTab" :tabs="tabData" style="margin-top: 8px;"/>
      <ContactTable v-show="activeTab === 'contact'" ref="contactTable" :is-page-edit="isPageEdit" v-model="contactData" :loading="contactLoading" :dept-tree-list="deptTreeList" :order-private-id="orderPrivateId" @orderPrivateIdChange="orderPrivateIdChange" @delContact="delContact"/>
      <PayerTable v-show="activeTab === 'payer'" ref="payerTable" v-model="payerData" :loading="payerLoading" :order-private-id="payerOrderPrivateId" @orderPrivateIdChange="payerOrderPrivateIdChange" @delPayer="delPayer"/>
      <EmptyPlaceholder v-if="emptyEditAuth" :empty-img="emptyImg" style="margin-top:20px;" text="您暂无可编辑模块，请联系管理员" image-size="90px"/>
    </div>
    <fixed-pagination class="fixed-bottom">
      <div class="create-customer-btn">
        <el-button v-if="!emptyEditAuth" :loading="loading" type="primary" class="submit-btn mobile-btn-flex" size="small" @click="toSave">保存</el-button>
        <el-button type="info" class="cancel-btn-style mobile-btn-flex" size="small" @click="toBack">取消</el-button>
      </div>
    </fixed-pagination>
    <CreateApproval ref="CreateApprovalRef" />
    <PreciseDialog :visible="showPreciseDialog" :precise-data="preciseData" @continueCreate="toSubmit(0)" @closePreciseData="closePreciseData"/>
  </div>
</template>
<script>
import Title from '@/components/Title';
import DetailTabs from '@/components/Common/baseComponent/DetailTabs';
import ContactTable from '../module/contactTable';
import PayerTable from '../module/payerTable';
import PreciseDialog from '../module/preciseDialog';
import {
  addClient, editClient, onlyClient, getClientInfo, getClientContacts, getClientPayers,
  getClientGroup, getList, getLevelList, repeatClientName
} from '@/api/customer';
import { getClientStatus } from '@/api/select';
import { getDepartmentAll } from '@/api/config';
import { supplierInfo } from '@/api/supplier';
import { mapState } from 'vuex';
import TagSelect from '@/components/Common/tagSelect';
import ElMessage from '@/utils/message';
import upAttachment from '@/components/Common/upAttachment/index';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import emptyImg from '@/assets/empty-data-icon.png';
import { hasRouteAuth } from '@/utils/permission';
import { TAG_MODULES } from '@/utils/const';
import { isObjEqual } from '@/utils/tools';
import mobileCreate from '@/mixins/mobileCreate';
import CreateApproval from '../cooperation/createApproval';
import { deepClone } from '@/utils';

export default {
  components: {
    Title,
    DetailTabs,
    ContactTable,
    PayerTable,
    TagSelect,
    upAttachment,
    PreciseDialog,
    EmptyPlaceholder,
    CreateApproval
  },
  mixins: [mobileCreate],
  props: {
    pageType: { // 如果值为component 则这个页面作为组建使用
      type: String,
      default: ''
    }
  },
  data() {
    return {
      emptyImg,
      TAG_MODULES,
      successRoute: 'customer',
      editCustomerForm: {
        clientType: '',
        clientName: '',
        clientStatus: '',
        clientGrade: null,
        clientSource: '',
        remark: '',
        oweAmount: '',
        accountPeriod: '',
        tag: [],
        invoiceInfo: {},
        groupId: [],
        actualClientRequired: 0
      },
      deptTreeList: [],
      clientLevelOptions: [],
      editCustomerRules: {
        clientType: [{ required: true, trigger: 'change', message: '请选择客户类型' }],
        clientName: [{ required: true, trigger: 'blur', message: '请输入客户的全称' }],
        clientStatus: [{ required: true, trigger: 'blur', message: '请填写客户状态' }]
      },
      levelRules: {
        clientGrade: [{ required: true, trigger: 'change', message: '请选择客户等级' }]
      },
      clientList: [
        { id: 0, value: '公司' },
        { id: 1, value: '个人' }
      ],
      clientStatusList: [
        { id: 0, name: '成交客户' },
        { id: 1, name: '无效客户' },
        { id: 2, name: '忠诚客户' },
        { id: 3, name: '潜在客户' },
        { id: 4, name: '持续跟进' },
        { id: 5, name: '初步接触' }
      ],
      title: '新增客户',
      customerId: '',
      isDisabled: false,
      loading: false,
      tagOptions: [],
      activeTab: 'contact',
      contactData: [], // 联系人列表数据
      delContactData: [], // 被删除的联系人数据
      contactDataOrigin: [], // 缓存联系人数据
      initLoading: false,
      contactLoading: false,
      payerLoading: false,
      payerData: [], // 付款人列表数据
      delPayerData: [], // 被删除的付款人数据
      payerDataOrigin: [], // 缓存付款人数据
      orderPrivateId: 1,
      payerOrderPrivateId: 1,
      isPageEdit: false,
      groupListCopy: [],
      groupList: [],
      preciseData: [],
      showPreciseDialog: false,
      customerInfoOrigin: {}, // 缓存客户数据
      initTabClick: true, // 第一次点击
      clientRepeatAuth: 0, // 客户是否重复
      dupNameCode: '', // 重名识别号
      clientCodeRepeat: 0, // 客户名称带识别号是否重复
      originClientName: '' // 编辑页接口返回的客户名称，用于对比输入前后的客户名称
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    emptyEditAuth() {
      return !this.hasRouteAuth(['crm:customer:clientInfo:read', 'crm:customer:levelInfo:read', 'crm:customer:invoiceInfo:read', 'crm:customer:contactsInfo:read', 'crm:customer:payerInfo:read']);
    },
    canEdit() {
      return this.isPageEdit && !this.hasRouteAuth('crm:customer:editClientName');
    },
    tabData() {
      const tabs = [];
      this.hasRouteAuth('crm:customer:contactsInfo:read') && tabs.push({ name: '联系人', id: 'contact' });
      this.hasRouteAuth('crm:customer:payerInfo:read') && tabs.push({ name: '付款人', id: 'payer', tooltip: '添加付款人之后，请联系财务启用该付款人，该客户即可核销该付款人流水' });
      return tabs;
    }
  },
  watch: {
    activeTab(newVal, oldVal) {
      if (this.customerId && newVal === 'payer' && this.initTabClick) {
        this.getPayerList();
        this.initTabClick = false;
      }
    },
    'editCustomerForm.clientGrade'(data) {
      this.$nextTick(() => {
        const value = typeof data === 'object' ? data.name : data;
        const targetList = this.clientLevelOptions.filter(i => i.name === value);
        const targetData = targetList[0] || {};
        this.editCustomerForm.oweAmount = targetData.oweAmount;
        this.editCustomerForm.accountPeriod = targetData.accountPeriod;
      });
    }
  },
  created() {
    if (this.$route.params.clientName) {
      this.editCustomerForm.clientName = this.$route.params.clientName;
    }
    this.getGroupData();
    this.setActiveTab(this.$route.query.activeTab);
    this.customerId = Number(this.$route.params.customerId) || '';
    if (this.$route.query.routeName || this.$route.params.routeName) {
      this.successRoute = this.$route.query.routeName || this.$route.params.routeName;
    }
    if (!this.customerId) {
      this.isPageEdit = false;
      const { supplierId } = this.$route.query;
      supplierId && this.querySupplierDetail(supplierId);
    } else {
      this.isPageEdit = true;
      this.title = '编辑客户';
      this.isDisabled = true;
      this.getContactList();
    }
    this.queryLevelAndInfo();
    this.queryDeptTreeList();
    this.clientStatusOption();
  },
  methods: {
    hasRouteAuth,
    formatTime(timestamp) {
      if (!timestamp) return;
      function add0(m) {
        return m < 10 ? '0' + m : m;
      }
      const time = new Date(timestamp);
      const y = time.getFullYear();
      const m = time.getMonth() + 1;
      const d = time.getDate();
      const h = time.getHours();
      const mm = time.getMinutes();
      const s = time.getSeconds();
      return y + '/' + add0(m) + '/' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
    },
    setActiveTab(tab) {
      const hasContactsAuth = hasRouteAuth('crm:customer:contactsInfo:read');
      const hasPayerAuth = hasRouteAuth('crm:customer:payerInfo:read');
      if (['contact', 'payer'].includes(tab)) {
        if (tab === 'payer' && !hasPayerAuth) {
          this.$message.warning('暂无付款人相关权限，请联系管理员');
          this.activeTab = hasContactsAuth ? 'contact' : '';
          return;
        } else if (tab === 'contact' && !hasContactsAuth) {
          this.$message.warning('暂无联系人相关权限，请联系管理员');
          this.activeTab = hasPayerAuth ? 'payer' : '';
          return;
        }
        this.activeTab = tab;
        return;
      }
      this.activeTab = hasContactsAuth ? 'contact' : hasPayerAuth ? 'payer' : '';
    },
    // [v3.6.4] 从供应商同步信息新建
    querySupplierDetail(id) {
      this.initLoading = true;
      supplierInfo(id).then(res => {
        if (res.code === 200) {
          const { supplierType } = res.data;
          this.editCustomerForm.clientName = res.data['channelName']; // 供应商名称 -> 客户名称
          if (supplierType === 1) { // 公司
            this.editCustomerForm.clientType = 0;
            this.$set(this.editCustomerForm.invoiceInfo, 'taxpayerNum', res.data['taxpayerIdentificationNumber']); // 纳税人识别号 -> 纳税人识别号
            this.$set(this.editCustomerForm.invoiceInfo, 'taxpayerAttachment', res.data['idCard']); // 营业执照 -> 一般纳税人证明
          } else if (supplierType === 0) { // 个人
            this.editCustomerForm.clientType = 1;
            this.$set(this.editCustomerForm.invoiceInfo, 'taxpayerNum', res.data['identityNumber']); // 身份证号 -> 身份证号
          }
        }
        this.initLoading = false;
      }).catch(() => {
        this.initLoading = false;
      });
    },
    queryClientDetail() {
      getClientInfo(this.customerId).then(({ code, message, data }) => {
        this.editCustomerForm = data;
        this.originClientName = data.clientName;
        if (this.editCustomerForm.clientGrade == null) {
          this.editCustomerForm.oweAmount = '';
          this.editCustomerForm.accountPeriod = '';
        }
        const temp = data.group ? data.group.map(item => {
          return item.id;
        }) : [];
        this.$set(this.editCustomerForm, 'groupId', temp);
        this.customerInfoOrigin = deepClone(this.editCustomerForm);
        this.dupNameFormat();
      });
    },
    getContactList() {
      this.contactLoading = true;
      getClientContacts(this.customerId, { page: 1, perPage: 0 }).then(res => {
        this.contactData = res.data.items.map(item => {
          item.department = this.formatTag(item.department);
          item.onlyRead = true;
          item.associateList = item.associate;
          if (item.coDepartment && item.coDepartment.length > 0) item.coDepartmentName = item.coDepartment.map(i => { return i.name; }).join();
          if (item.coDepartment && item.coDepartment.length > 0) item.coDepartment = item.coDepartment.map(i => { return i.id; });
          item.orderPrivateId = ++this.orderPrivateId;
          return item;
        });
        this.contactLoading = false;
        this.contactDataOrigin = deepClone(this.contactData);
        this.$refs['contactTable'].setFirstSelectTag();
      }).catch(err => {
        this.contactLoading = false;
        console.log(err);
      });
    },
    getPayerList() {
      this.payerLoading = true;
      getClientPayers(this.customerId, { page: 1, perPage: 0 }).then(res => {
        this.payerData = res.data.items.map(item => {
          item.createTime = this.formatTime(item.createTime);
          item.associateList = item.associate;
          if (item.coDepartment && item.coDepartment.length > 0) item.coDepartmentName = item.coDepartment.map(i => { return i.name; }).join();
          if (item.coDepartment && item.coDepartment.length > 0) item.coDepartment = item.coDepartment.map(i => { return i.id; });
          item.orderPrivateId = ++this.payerOrderPrivateId;
          return item;
        });
        this.payerLoading = false;
        this.payerDataOrigin = deepClone(this.payerData);
        this.$refs['payerTable'].setFirstSelectTag();
      }).catch(err => {
        this.payerLoading = false;
        console.log(err);
      });
    },
    // 等级有设置岗位且不包含当前用户岗位时，不可选
    canSelectLevel(data) {
      if (!data.post || (Array.isArray(data.post) && !data.post.length)) return true;
      return data.post.includes(this.userInfo.post);
    },
    orderPrivateIdChange(num) {
      if (!num) return;
      this.orderPrivateId = num;
    },
    payerOrderPrivateIdChange(num) {
      if (!num) return;
      this.payerOrderPrivateId = num;
    },
    clientStatusOption() {
      getClientStatus().then((res) => {
        this.clientStatusList = res.data;
      });
    },
    onlyClientName() {
      onlyClient(this.editCustomerForm.clientName).then(({ code, data }) => {
        if (data.status) {
          this.$message.warning(`客户名称 ${this.editCustomerForm.clientName} 重复，请核对!`);
        } else {
          return false;
        }
      }, result => {
        this.$message.error(result.message);
      });
    },
    async add(params, isPrecise) {
      if (isPrecise) {
        try {
          const clientName = this.dupNameCode ? `${this.editCustomerForm.clientName}(${this.dupNameCode})` : this.editCustomerForm.clientName;
          const res = await getList({ page: 1, perPage: 10, clientName, preciseQuery: 1, authControl: 1 });
          if (res.data.item) {
            this.showPreciseDialog = true;
            this.preciseData.push(res.data.item);
            this.loading = false;
            return new Promise((resolve, reject) => {
              reject();
            });
          }
        } catch (err) {
          console.log(err);
          this.loading = false;
        }
      }
      try {
        const res = await addClient(params);
        if (res.code === 200) {
          this.loading = false;
          this.$message.success('添加成功');
          if (this.pageType === 'component') {
            this.$emit('submit', res.data || {});
            return;
          }
          if (this.successRoute === 'customer') {
            this.$router.push({
              name: 'customer'
            });
          } else {
            this.$router.push({
              name: this.successRoute,
              params: { customerId: this.customerId }
            });
          }
        }
      } catch (err) {
        this.loading = false;
      }
    },
    edit(params) {
      editClient(this.customerId, params).then(({ code, message }) => {
        this.loading = false;
        this.$message.success('修改成功');
        this.$route.params.editClient = true;
        if (this.successRoute === 'customer') {
          this.$router.push({
            name: 'customer'
          });
        } else {
          this.$router.push({
            name: this.successRoute,
            params: { customerId: this.customerId },
            query: { active: this.activeTab }
          });
        }
      }, result => {
        this.loading = false;
        // this.$message.error(result.message);
      });
    },
    contrastData(cache, contactData) {
      if (!contactData || !contactData.length) {
        return;
      }
      // 传进来的数据是数组，需要给每条数据对比，只需要对比cache里有的数据
      // 找出cache里有的数据
      const data = contactData.filter(item => {
        return cache.some(ele => ele.id === item.id);
      });
      // 给每条数据做对比，看是否修改
      const len = data.length;
      for (let i = 0; i < len; i++) {
        const obj1 = data[i];
        const obj2 = cache[i];
        const keys = Object.keys(obj1);
        // 遍历属性进行比较
        for (const key of keys) {
          const isObj1 = Object.prototype.toString.call(obj1[key]) === '[object Object]';
          const isObj2 = Object.prototype.toString.call(obj2[key]) === '[object Object]';
          if (Array.isArray(obj1[key]) || Array.isArray(obj2[key])) {
            if (!isObjEqual(obj1[key], obj2[key])) {
              data[i].modified = true;
              break;
            }
          } else if ((!obj1[key] && obj2[key] && isObj2) || (!obj2[key] && obj1[key] && isObj1)) {
            data[i].modified = true;
            break;
          } else if ((obj1[key] || obj2[key]) && (!isObj1 && !isObj2) && obj1[key] !== obj2[key]) {
            // 如果属性值前后不一致，该条数据modified设为true
            data[i].modified = true;
            break;
          }
        }
      }
    },
    contrastInfo(cache, infoData) {
      // 获取cache属性集合
      const keys = Object.keys(cache);
      // 遍历属性进行比较
      for (const key of keys) {
        if (['contactObj', 'payers'].includes(key)) {
          continue;
        }
        if (Array.isArray(cache[key])) {
          if (!isObjEqual(cache[key], infoData[key])) {
            this.editCustomerForm.modified = true;
            break;
          }
        } else if (cache[key] && typeof cache[key] === 'object') {
          this.contrastInfo(cache[key], infoData[key]);
        } else if ((typeof cache[key] === 'number' && cache[key] !== Number(infoData[key])) || (typeof cache[key] !== 'number' && (cache[key] || infoData[key]) && cache[key] !== infoData[key])) {
          // 数字对比 || 不是数字对比，则要有值且值不一样
          // 如果属性值前后不一致，该条数据modified设为true
          // infoData.modified = true;
          this.editCustomerForm.modified = true;
          break;
        }
      }
    },
    handleContrast(contactData, payerData) {
      this.contrastData(this.contactDataOrigin, contactData);
      this.contrastData(this.payerDataOrigin, payerData);
      this.contrastInfo(this.customerInfoOrigin, this.editCustomerForm);
    },
    toSubmit(isPrecise = 1) {
      let contactData = JSON.parse(JSON.stringify(this.contactData));
      // 处理联系人列表的协作人更新协作部门问题，获取每条联系人的当前协作人，取其currentDepartment就是最新的部门
      contactData.forEach(item => {
        if (item.associate) {
          let temp = [];
          item.associate = item.associate.map(item => {
            if (item.currentDepartment) {
              temp = temp.concat(item.currentDepartment);
            }
            return item.id;
          });
          item.coDepartment = temp.map(item => item.id);
        }
      });
      let payers = JSON.parse(JSON.stringify(this.payerData));
      // 处理付款人列表的协作人更新协作部门问题，获取每条付款人的当前协作人，取其currentDepartment就是最新的部门
      payers.forEach(item => {
        if (item.associate) {
          let temp = [];
          item.associate = item.associate.map(item => {
            if (item.currentDepartment) {
              temp = temp.concat(item.currentDepartment);
            }
            return item.id;
          });
          item.coDepartment = temp.map(item => item.id);
        }
      });
      this.handleContrast(contactData, payers);
      contactData = contactData.concat(this.delContactData).map(item => {
        if (item.contactPerson) item.contactPerson = item.contactPerson.trim();
        item.createTime = item.createTime === '--' ? null : item.createTime;
        delete item.department;
        delete item.isAdd;
        delete item.associateList;
        return item;
      });
      const params = JSON.parse(JSON.stringify(this.editCustomerForm));
      params.contactObj = contactData;
      payers = payers.concat(this.delPayerData).map(item => {
        delete item.associateList;
        return item;
      });
      params.payers = payers;
      params.tag = params.tag ? params.tag.map(item => {
        return item.id;
      }) : [];
      if (params.accountPeriod) params.accountPeriod = Number(params.accountPeriod);
      if (this.dupNameCode && params.clientType) {
        params.clientName += `(${this.dupNameCode})`;
      }
      if (!this.customerId) {
        this.loading = true;
        this.add(params, isPrecise);
      } else {
        this.loading = true;
        this.edit(params);
      }
    },
    toSave: _.debounce(function() {
      // 客户名称重复或客户名称+识别号重复，不让提交
      const repeatRes = this.editCustomerForm.clientType ? this.clientCodeRepeat : this.clientRepeatAuth;
      if (repeatRes) {
        let msg;
        if (repeatRes === 1) {
          msg = '已拥有该客户的权限，请勿重复创建';
        } else if (repeatRes === 2) {
          msg = '已存在相同名称客户，无需新建客户，请申请协作权限';
        }
        ElMessage.error(msg);
        return;
      }
      if (!hasRouteAuth('crm:customer:clientInfo:read')) {
        this.$message.warning('您没有客户信息权限，请联系管理员');
        return;
      }
      if (!hasRouteAuth('crm:customer:contactsInfo:read')) {
        this.$message.warning('您没有联系人信息权限，请联系管理员');
        return;
      }
      // this.showPreciseDialog = true;
      try {
        const params = [];
        params.push(this.$refs['editCustomerForm'].validate());
        if (hasRouteAuth('crm:customer:levelInfo:read')) { // 等级账期
          this.$refs['levelInfoFormRef'] && params.push(this.$refs['levelInfoFormRef'].validate());
        } else { // 没有权限，默认回填等级最低的客户等级
          if (this.clientLevelOptions.length) {
            const selectItem = this.clientLevelOptions.find(i => !!i.isDefault);
            if (selectItem && this.canSelectLevel(selectItem)) {
              this.$set(this.editCustomerForm, 'clientGrade', selectItem.name);
            } else {
              this.editCustomerForm.clientGrade = this.clientLevelOptions[this.clientLevelOptions.length - 1].name;
            }
          } else {
            this.editCustomerForm.clientGrade = '新客户';
          }
        }
        if (hasRouteAuth('crm:customer:payerInfo:read')) { // 付款人
          this.$refs['payerTable'] && params.push(this.$refs['payerTable'].validate());
        }
        Promise.all(params).then(res => {
          const validateResult = res.every(item => !!item);
          if (validateResult) {
            const dupNameCodeCheck = repeatRes && this.editCustomerForm.clientType ? !!this.dupNameCode : true;
            if (dupNameCodeCheck) {
              this.toSubmit();
            } else {
              ElMessage.warning('请填写重名识别号');
            }
          } else {
            return false;
          }
        }).catch((error) => {
          ElMessage.warning('请检查信息是否填写完整');
          console.log('error', error);
        });
      } catch (error) {
        console.log(error);
      }
    }, 500),
    getFormPromise(form) {
      return form.validate();
    },
    statusChange() {
      this.$refs.editCustomerForm.validateField('clientStatus');
    },
    toBack() {
      if (this.pageType === 'component') {
        this.$emit('close');
        return;
      }
      if (this.successRoute === 'customer') {
        this.$router.push({
          name: 'customer'
        });
      } else {
        this.$router.push({
          name: this.successRoute,
          params: { customerId: this.customerId }
        });
      }
    },
    channelInputLimit(e) {
      const key = e.key;
      // 不允许输入'e'和'.'
      if (key === 'e' || key === '.' || key === '+' || key === '-') {
        e.returnValue = false;
        return false;
      }
      return true;
    },
    // 获取所属部门
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      });
    },
    // 客户等级和详情
    async queryLevelAndInfo() {
      try {
        const levelInfoData = await getLevelList();
        this.clientLevelOptions = levelInfoData && levelInfoData.data || [];
        this.isPageEdit && this.queryClientDetail();
      } catch (e) {
        this.isPageEdit && this.queryClientDetail();
      }
    },
    delContact(val) {
      this.delContactData.push(val);
    },
    delPayer(val) {
      this.delPayerData.push(val);
    },
    formatTag(val) {
      if (val && val instanceof Array) {
        return val.map(item => {
          return item.name;
        }).join(',');
      } else {
        return '--';
      }
    },
    completeSetData({ data, fileName }, key) {
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      if (this.editCustomerForm.invoiceInfo[key]) {
        this.editCustomerForm.invoiceInfo[key].push(fileList);
      } else {
        this.$set(this.editCustomerForm.invoiceInfo, key, [fileList]);
      }
      key === 'certificateFile' && this.$refs['applicationInfoForm'].validateField(key);
    },
    removeFileList({ file, index }, key) {
      this.editCustomerForm.invoiceInfo[key].splice(index, 1);
      key === 'certificateFile' && this.$refs['applicationInfoForm'].validateField(key);
    },
    async getGroupData() {
      const { data } = await getClientGroup();
      this.groupList = data;
      this.groupListCopy = data;
    },
    getGroupList(val) {
      const el = this.$refs.groupSelectRef.popperElm;
      if (val && val.length > 6) {
        el.style.visibility = 'visible';
        this.groupList = this.groupListCopy.filter(it => it.name.includes(val));
      } else {
        el.style.visibility = 'hidden';
      }
    },
    groupFocus(e) {
      const el = this.$refs.groupSelectRef.popperElm;
      if (!e.target.value || e.target.value.length < 7) {
        el.style.visibility = 'hidden';
      } else {
        el.style.visibility = 'visible';
      }
    },
    closePreciseData() {
      this.showPreciseDialog = false;
      this.preciseData = [];
    },
    toCreateApproval(name) {
      this.$refs.CreateApprovalRef.openDialog(name);
    },
    async checkNameRepeat() {
      if (this.editCustomerForm.clientName) {
        this.editCustomerForm.clientName = this.editCustomerForm.clientName.trim();
      }
      const name = this.dupNameCode ? `${this.editCustomerForm.clientName}(${this.dupNameCode})` : this.editCustomerForm.clientName;
      if (name === this.customerInfoOrigin.clientName) {
        if (this.editCustomerForm.clientType) {
          this.clientCodeRepeat = 0;
        } else if (!this.editCustomerForm.clientType) {
          this.clientRepeatAuth = 0;
        }
        return;
      }
      try {
        const res = await repeatClientName({ clientName: name });
        if (res.code === 200 && res.data) {
          if (this.editCustomerForm.clientType) {
            this.clientCodeRepeat = res.data.isRepeat;
          } else if (!this.editCustomerForm.clientType) {
            this.clientRepeatAuth = res.data.isRepeat;
          }
        }
      } catch (error) {
        this.clientRepeatAuth = false;
      }
    },
    inputClientName(val) {
      let str;
      str = val.replace(/[()]/g, ''); // 去除英文括号
      str = str === '' ? null : str;
      this.editCustomerForm.clientName = str;
    },
    dupNameFormat() {
      if (this.editCustomerForm.clientType && this.editCustomerForm.clientName.includes('(')) {
        this.clientCodeRepeat = 1;
        // const pattern = /([^(]+)(\(\d+\))/;
        const pattern = /([^(]+)(\(.+\))/;
        const result = this.editCustomerForm.clientName.match(pattern);
        this.editCustomerForm.clientName = result[1];
        this.dupNameCode = result[2].replace(/[()]/g, '');
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.create-custom-box{
  margin: 16px;
}
.create-customer {
  min-height: calc(100vh - 116px);
  margin-bottom: 20px;
  padding: 24px 24px 50px 24px;
  background-color: #fff;
  box-shadow:2px 4px 13px 0px rgba(221,225,234,1);
  &::v-deep{
    .el-form {
      .customer-form {
        // min-height: calc(100vh - 116px);
        .el-input {
          width: 240px;
        }
        .el-select {
          height: 32px;
          .el-input {
            height: 32px;
            line-height: 32px;
            width: 240px;
          }
          .el-tag {
            background-color: #eff3fb;
            color: #333;
            position: relative;
            &:first-of-type{
              padding-right: 20px;
            }
            .el-select__tags-text {
              display: inline-block;
              max-width: 120px;
              white-space: nowrap;
              text-overflow: ellipsis;
              overflow: hidden;
            }
            .el-tag__close {
              position: absolute;
              top: 4px;
              right: 0px;
              font-size: 16px;
              background-color: transparent;
              color: #333;
            }
          }
        }
        .el-form-item {
          margin-bottom: 24px;
          &.contact{
            position: relative;
            margin-bottom: 0;
          }
          .el-input__icon {
            line-height: 24px;
          }
          input {
            width: 240px;
            line-height: 16px;
          }
        }
        .add-btn {
          width: 32px;
          height: 32px;
          position: relative;
          background-color: #EFF3FB;
          border: none;
          border-radius: 4px;
          color: #406eff;
          font-size: 16px;
          font-weight: bold;
          cursor: pointer;
        }
      }
      .el-radio__label {
        font-size: 14px;
      }
    }
    .client-textarea {
      width: 240px;
    }
  }
  .indentation-form-item {
    ::v-deep .el-form-item {
      label {
        line-height: 1.2 !important;
      }
    }
  }
  .title-tip {
    margin-bottom: 16px;
    p {
      margin: 0 0 0 8px;
      color: #FF4E5F;
    }
  }
}
.width240 {
  width: 240px;
  &::v-deep {
    .el-input, .el-input__inner {
      // width: auto !important;
      width: 116px !important;
    }
  }
}
.client-name {
  position: relative;
  .name-tip {
    position: absolute;
    left: 0;
    top: 26px;
    color: #f56C6C;
    font-size: 12px;
  }
}
.relative {
  position: relative;
}
.footer-tip {
  position: absolute;
  bottom: -20px;
  line-height: 20px;
  display: flex;
  font-size: 12px;
  color: #F56C6C;
  white-space: nowrap;
}

.component-class {
  .create-customer {
    box-shadow: none;
    padding: 0 0 50px 0;
  }
  .responsive-col-medium-8 {
    height: 56px;
  }
}
.mobile-create {
  .mobile-tip {
    left: -30px !important;
  }
  .create-customer {
    padding: 16px 24px;
  }
  .mobile-title-top {
    padding-top: 4px;
  }
  ::v-deep {
    .customer-table-box .add-btn {
      position: static;
      margin-top: 12px;
    }
  }
}
.fixed-bottom{
  .create-customer-btn{
    display: flex;
    width: 100%;
    justify-content: center;
  }
}
.contact{
  .el-button--text{
    color: #192452;
  }
}
</style>
